<template>
  <div class="container">
    <div class="logs">
      <pre v-if="logs">{{ logs }}</pre>
    </div>
    <div class="buttons">
      <van-button round block type="primary" @click="viewOrLoadLogs">{{ buttonText }}</van-button>
      <van-button round block type="danger" @click="clearLogs">清空日志</van-button>
    </div>
    <div v-if="noMoreLogs" class="end-of-logs">到底了</div>
  </div>
</template>

<script>
import api from '../api';
import { showSuccessToast, showFailToast } from 'vant';

export default {
  name: 'ViewLogs',
  data() {
    return {
      logs: '',
      start: 0,
      length: 1000,
      noMoreLogs: false,
      buttonText: '查看日志',
    };
  },
  methods: {
    async viewOrLoadLogs() {
      if (this.start === 0) {
        this.logs = '';
        this.noMoreLogs = false;
      }
      await this.loadMoreLogs();
    },
    async loadMoreLogs() {
      try {
        const response = await api.get('/api/view-logs', {
          params: { start: this.start, length: this.length }
        });
        if (response.data.logs.length === 0) {
          this.noMoreLogs = true;
          showSuccessToast('到底了');
        } else {
          this.logs += response.data.logs;
          this.start += this.length;
          this.buttonText = '加载更多';
        }
      } catch (error) {
        showFailToast('Failed to load logs');
      }
    },
    clearLogs() {
      this.logs = '';
      this.start = 0;
      this.noMoreLogs = false;
      this.buttonText = '查看日志';
      showSuccessToast('日志已清空');
    },
  },
};
</script>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  height: 100vh;
}

.logs {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  background-color: #f5f5f5;
  height: calc(100vh - 180px); /* 100vh 减去按钮区域的高度 */
}

.buttons {
  background-color: #fff;
  padding: 16px;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  gap: 5px;
  position: relative;
  bottom: 5vh;
  height: 150px;
  
}

.end-of-logs {
  text-align: center;
  margin-top: 10px;
  color: gray;
}
</style>
